"use client";

import React, { useState, useRef, useEffect } from "react";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
import { LuckyWheel } from "@lucky-canvas/react";
import { queryRaffleAwardList, draw } from "@/apis";
import { RaffleAwardVO } from "@/types/RaffleAwardVO";

// @ts-ignore
export default function LuckeyWheelPage({handleRefresh}) {
  const [activityId, setActivityId] = useState<number | null>(null);
  const [userId, setUserId] = useState<string | null>(null);
  const [prizes, setPrizes] = useState([]);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const myLucky = useRef<any>(null);

  const [blocks] = useState([{ padding: "10px", background: "#869cfa" }]);
  const [buttons] = useState([
    { radius: "40%", background: "#617df2" },
    { radius: "35%", background: "#afc8ff" },
    {
      radius: "30%",
      background: "#869cfa",
      pointer: true,
      fonts: [{ text: "开始", top: "-10px" }],
    },
  ]);

  const queryRaffleAwardListHandle = async () => {
    if (activityId === null || userId === null) {
      console.log("activityId 或 userId 为 null");
      return;
    }
    console.log("开始查询奖品列表...");
    const result = await queryRaffleAwardList(userId, activityId);
    const { code, info, data } = await result.json();
    console.log("API 返回结果:", { code, info, data });
    if (code !== "0000") {
      window.alert("获取抽奖奖品列表失败 code:" + code + " info:" + info);
      return;
    }

    // 创建一个新的奖品数组
    const prizes = data.map((award: RaffleAwardVO, index: number) => {
      const background = index % 2 === 0 ? '#e9e8fe' : '#b8c5f2';
      return {
        background: background,
        fonts: [{ id: award.awardId, text: award.awardTitle, top: '15px' }]
      };
    });

    console.log("奖品列表:", prizes);  // 打印奖品列表
    setPrizes(prizes);
  };


  // 调用随机抽奖
  const randomRaffleHandle = async () => {
    const result = await draw(userId, activityId);
    const {code, info, data} = await result.json();
    if (code != "0000") {
      window.alert("随机抽奖失败 code:" + code + " info:" + info)
      return;
    }
    handleRefresh()
    // 为了方便测试，mock 的接口直接返回 awardIndex 也就是奖品列表中第几个奖品。
    return data.awardIndex - 1;
  }

  // 在客户端获取 activityId和userId
  useEffect(() => {
    if (typeof window !== "undefined") {
      const queryParams = new URLSearchParams(window.location.search);
      const activityIdFromQuery = Number(queryParams.get("activityId"));
      const userIdFromQuery = String(queryParams.get("userId"));
      setActivityId(activityIdFromQuery);
      setUserId(userIdFromQuery);
      console.log("activityIdFromQuery:", activityIdFromQuery, "userIdFromQuery:", userIdFromQuery);
    }
    queryRaffleAwardListHandle().then(() => {});
    console.log("加载完成后的奖品列表:", prizes);
  }, [activityId, userId]);


  return (
      <div>
        <LuckyWheel
            ref={myLucky}
            width="300px"
            height="300px"
            blocks={blocks}
            prizes={prizes}
            buttons={buttons}
            onStart={() => {
              if (myLucky.current) {
                myLucky.current.play();
              }
              setTimeout(() => {
                randomRaffleHandle().then((prizeIndex) => {
                  if (myLucky.current) {
                    myLucky.current.stop(prizeIndex);
                    const timer = setTimeout(() => {
                      handleRefresh()
                    }, 550);

                    // 清除定时器，以防组件在执行前被卸载
                    return () => clearTimeout(timer);
                  }
                });
              }, 2500);
            }}
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            onEnd={
              // @ts-ignore
              prize => {
                // 加载数据
                queryRaffleAwardListHandle().then(() => {
                });
                // 展示奖品
                alert('恭喜抽中奖品💐【' + prize.fonts[0].text+'】')
              }
            }
        />
      </div>
  );
}
